<script setup lang="ts">
import axiosInstance from "@utils/axiosInstance.js";
import {globalConst} from "@constants/globalConst.js";
import ResponseResult from "@models/ReturnResult.js";
import {Resources} from "@models/Resources.js";
import {ref} from "vue";
import type {Tag} from "@models/Tag.js";
import {getData, saveData} from "@stores/dataStorage.js";
import {isNull} from "@utils/stringUtil.js";
import ResourceImgManagement from "@components/resourceImgManagement.vue";
import {useGlobalConfirm} from "@utils/ConfirmDialogPlugin.js";
import ResourceFileManagement from "@components/resource-file-management.vue";

interface DTOResources {
  // 资源ID（整数类型）
  rId?: number;
  // 资源名称（字符串，非空）
  rName: string;
  // 资源发行商/厂商名称（字符串，非空）
  rManufacturer: string;
  // 资源类型（字符串，非空）
  rType: string;
  // 资源简介（字符串，非空）
  rIntroduction: string;
  // 标签ID列表（整数数组，默认空数组）
  tags: number[];
  // 外部资源价格（整数，范围1-100）
  linkPrice?: number;
  // 本地资源下载价格（整数，范围5-100）
  downloadLocallyPrice?: number;
}

let id = -1
const params = new URLSearchParams(window.location.search)
let isAdd = ref(false)
try {
  id = parseInt(<string>params.get('rId'))
} catch (error) {
  id = -1
}
isAdd.value = id === -1

const tagList = ref<Tag[]>([])
const resource = ref<DTOResources>({
  downloadLocallyPrice: 0, linkPrice: 0, rId: -1, rIntroduction: "", rManufacturer: "", rName: "", rType: "", tags: []
})
const typeSelectList = ref<string[]>([])
const hasError = ref(false)
let resultMsg = new Resources()
if (!isAdd.value) {
  const res = await axiosInstance.get(`${globalConst.baseUrl}index/getResources/${id}`)
  const result = ResponseResult.fromApiResponse(res.data)
  if (result.isSuccess()) {
    if (result.returnResult == null) {
      alert('您请求的资源不存在, 换一个试试,已经自动启动添加模式')
    } else {
      resultMsg = Resources.fromApiResponse(result.returnResult)
      isAdd.value = false
      resource.value.rId = resultMsg.rId
      resource.value.rName = resultMsg.rName
      resource.value.rManufacturer = resultMsg.rManufacturer
      resource.value.rIntroduction = resultMsg.rIntroduction
      resource.value.rType = resultMsg.rType
      resource.value.tags = resultMsg.tags.map((tag: Tag) => tag.tagId)
      resource.value.linkPrice = resultMsg.resourceExtensionInformation.linkPrice
      resource.value.downloadLocallyPrice = resultMsg.resourceExtensionInformation.downloadLocallyPrice
    }
  }
} else
  resource.value = {
    downloadLocallyPrice: 10,
    linkPrice: 5,
    rId: -1,
    rIntroduction: "",
    rManufacturer: "",
    rName: "",
    rType: "",
    tags: []
  }//新建空资源

try {
  let tags = getData('tagList')
  if (isNull(tags)) {
    const response = await axiosInstance.get(`${globalConst.baseUrl}select/getTag`)
    const r = ResponseResult.fromApiResponse(response.data)
    if (r.isSuccess()) {
      tags = r.returnResults
      saveData('tagList', tags)
    } else {
      alert('资源管理页面加载失败!' + r.msg)
      hasError.value = true
    }
    await axiosInstance.get(`${globalConst.baseUrl}select/getTypeMsg`).then(
        (r) => {
          const ref = ResponseResult.fromApiResponse<string>(r.data);
          if (ref.isSuccess()) {
            typeSelectList.value = ref.returnResults
          } else {
            alert('资源管理页面加载失败!' + ref.msg)
            hasError.value = true
          }
        }
    )
  }
  if (!tags || tags.length === 0) {
    alert('资源管理页面加载失败!!')
    hasError.value = false
  } else {
    tags.sort((a: Tag, b: Tag) => a.tagId - b.tagId)
    tagList.value = tags
  }
} catch (error) {
  console.error('加载标签失败:', error)
  alert('资源管理页面加载失败，请稍后重试')
  hasError.value = false
}

function clsSelectTag() {
  resource.value.tags = []
}

function submitResource() {
  //检查信息
  let upUrl
  if (isAdd.value)
    upUrl = 'user/resources/add'
  else
    upUrl = 'user/resources/update'
  if (isNull(resource.value.rName)) {
    alert('资源名称不可为空');
    return
  }
  if (isNull(resource.value.rManufacturer)) {
    alert('资源发行商/厂商名称不可为空');
    return
  }
  if (isNull(resource.value.rType)) {
    alert('资源类型不可为空');
    return
  }
  if (isNull(resource.value.rIntroduction)) {
    alert('资源简介不可为空');
    return
  }

  // 2. tags 字段校验（必须为数组，允许空数组）
  if (!Array.isArray(resource.value.tags)) {
    alert('标签列表必须为数组类型');
    return
  }

  // 3. linkPrice 校验（可选字段，若存在则需符合范围）
  if (!isNull(resource.value.linkPrice)) {
    if (!Number.isInteger(resource.value.linkPrice)) {
      alert('外部资源价格必须为整数');
      return
    }
    if (<number>resource.value.linkPrice < 1 || <number>resource.value.linkPrice > 100) {
      alert('外部资源价格范围必须为1-100');
      return
    }
  }
  if (!isNull(resource.value.downloadLocallyPrice)) {
    if (!Number.isInteger(resource.value.downloadLocallyPrice)) {
      alert('本地资源下载价格必须为整数');
      return
    }
    if (<number>resource.value.downloadLocallyPrice < 5 || <number>resource.value.downloadLocallyPrice > 100) {
      alert('本地资源下载价格范围必须为5-100');
      return
    }
  }
  axiosInstance.post(globalConst.baseUrl + upUrl, {
    "rId": isAdd.value ? -1 : id,
    'rName': resource.value.rName,
    'rManufacturer': resource.value.rManufacturer,
    'rType': resource.value.rType,
    'rIntroduction': resource.value.rIntroduction,
    'tags': resource.value.tags,
    'linkPrice': resource.value.linkPrice,
    'downloadLocallyPrice': resource.value.downloadLocallyPrice,
  }).then((r) => {
    const ref = ResponseResult.fromApiResponse(r.data)
    alert(ref.msg)
  })
}

async function toggle() {
  const r = useGlobalConfirm()
  if (!(await r('您确定要切换到' + (isAdd.value ? '修改' : '添加') + '模式吗?\n所有未保存和提交的数据将会丢失', {
        trueText: '是的,我确定',
        falseText: '取消操作'
      }
  )))
    return
  if (isAdd.value) {//切换为修改
    //新建而不是直接使用防止意外修改
    const value = Resources.fromApiResponse(resultMsg);
    resource.value.rId = value.rId
    resource.value.rName = value.rName
    resource.value.rManufacturer = value.rManufacturer
    resource.value.rIntroduction = value.rIntroduction
    resource.value.rType = value.rType
    resource.value.tags = value.tags.map((tag: Tag) => tag.tagId)
    resource.value.linkPrice = value.resourceExtensionInformation.linkPrice
    resource.value.downloadLocallyPrice = value.resourceExtensionInformation.downloadLocallyPrice
  } else {//切换为添加
    resource.value = {
      downloadLocallyPrice: 0,
      linkPrice: 0,
      rId: -1,
      rIntroduction: "",
      rManufacturer: "",
      rName: "",
      rType: "",
      tags: []
    }
  }
  isAdd.value = !isAdd.value
}
</script>

<template>
  <div v-if="!hasError">
    <div>
      <button @click="toggle">点击切换为资源添加/修改页面</button>
      <h2 class="resourceTitle" v-if="!isAdd">编辑ID为: [{{ resource.rId }}]的资源信息</h2>
      <h2 class="resourceTitle" v-else>添加资源信息</h2>
    </div>

    <div class="form-group">
      <label for="rName">资源名称:</label>
      <input type="text" id="rName" v-model="resource.rName"/>
    </div>

    <div class="form-group">
      <label for="rManufacturer">资源发行商/会社/作者信息:</label>
      <input type="text" id="rManufacturer" v-model="resource.rManufacturer"/>
    </div>

    <div class="form-group">
      <select v-model="resource.rType">
        <option v-for="type in typeSelectList" :key="type" :value="type">{{ type }}</option>
        <option value="null"> 不限</option>
      </select>
    </div>
    <p for="rType">资源定价:</p>
    <div class="form-group">
      <label for="rType">外部下载链接价格设置:</label>
      <input type="number" v-model="resource.linkPrice"/>
    </div>
    <div class="form-group">
      <label for="rType">本地下载链接价格设置:</label>
      <input type="number" v-model="resource.downloadLocallyPrice"/>
    </div>


    <br>资源标签(tag):
    <p>当前已选择标签数量:{{ resource.tags.length }}</p>
    <button @click="clsSelectTag">清空标签选项</button>
    <div>
      <table>
        <tr v-for="row in Math.ceil(tagList.length / 5)" :key="'row-' + row">
          <td v-for="col in 5" :key="'tag-' + (row-1)*5 + (col-1)">
            <template v-if="tagList[(row-1)*5 + (col-1)]">
              <label :for="'tag_' + tagList[(row-1)*5 + (col-1)].tagId">
                <input
                    type="checkbox"
                    :id="'tag_' + tagList[(row-1)*5 + (col-1)].tagId"
                    v-model="resource.tags"
                    :value="tagList[(row-1)*5 + (col-1)].tagId"
                />
                {{ tagList[(row - 1) * 5 + (col - 1)].tagId }}:
                {{ tagList[(row - 1) * 5 + (col - 1)].tagName }}
              </label>
            </template>
          </td>
        </tr>
      </table>
    </div>
    <!-- 简介 -->
    <div class="form-group">
      <label for="rIntroduction">简介:</label>
      <textarea id="rIntroduction" v-model="resource.rIntroduction" rows="5"></textarea>
    </div>
    <button @click="submitResource()" type="button">{{ isAdd ? '录入资源' : '提交修改' }}</button>
    <ResourceImgManagement :r-id="id" v-if="!isAdd"/>
    <resource-file-management :r-id="id" v-if="!isAdd"/>
  </div>
  <div v-else>
    <h1>页面加载失败!请稍后重试</h1>
  </div>
</template>

<style scoped>

</style>
